<?php

include_once('../../../notex.php');
$notex = new NOTEX();

// Describe how to use this script

$params = array(
    'db_user'  => 'The database username',
    'db_pass'  => 'The database password',
    'db_host'  => 'The database host',
    'database' => 'The database name',
    'sql'      => 'SQL to execute',
);
$notex->usage('mysql.php will run your SQL and return any results. The "db_host" parameter defaults to the localhost.', $params);

// Get the MySQL parameters

$db_user = param('db_user');
$db_pass = param('db_pass');
$db_host = param('db_host', 'localhost');
$database = param('database');
$sql = stripslashes(param('sql'));

if (!$db_user) $notex->error('No "db_user" parameter');
if (!$database) $notex->error('No "database" parameter');
if (!$sql) $notex->error('No "sql" parameter');

// Connect to MySQL and run the SQL query

mysql_connect($db_host, $db_user, $db_pass);
mysql_select_db($database);
$res = mysql_query($sql);
$selected = 0;
$status = 'good';

// Format results as XML

$out = "<result>\n";
if (!is_bool($res))
{
    $out .= "  <objects>\n";
    while ($obj = mysql_fetch_object($res))
    {
        $out .= "    <object>\n";
        while (list($key, $value) = each($obj))
        {
            $value = str_replace(array('&',    '<',    '>'),
                                 array('&amp', '&lt;', '&gt;'), $value);
            $out .= "      <$key>$value</$key>\n";
        }
        $out .= "    </object>\n";
    }
    $out .= "  </objects>\n";
    $selected = mysql_num_rows($res);
}
else // it's true or false...
{
    $status = $res ? 'good' : 'bad';
}

// Add info about the rows affected, any insert ID and the status

$affected = mysql_affected_rows();
$insert_id = mysql_insert_id();
$error = mysql_error();
$out .= "  <info selected=\"$selected\" affected=\"$affected\" insert_id=\"$insert_id\" status=\"$status\" error=\"$error\" />\n";
$out .= "</result>\n";

// Close the databas connection

mysql_close();

// Print the output as XML data

header('Content-type: text/xml');
print $out;

// END
